package com.bridgetree.jubaocrm.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.bridgetree.jubaocrm.R;
import com.bridgetree.jubaocrm.model.CRMUserBaseInfo;
import com.bridgetree.jubaocrm.service.Network;
import com.bridgetree.jubaocrm.util.LoginError;
import com.bridgetree.jubaocrm.util.LoginInterface;

/**
 * 个人档案
 */
public class PersonDocumentActivity extends Activity {
	private final String TAG = "PersonDocumentActivity";
	private Context mContext;
	private LoginInterface mLoginInterface;
	private InputMethodManager mInputMethodManager;
	private TextView main_name;
	private TextView main_tel;
	private TextView main_email;
	private TextView main_sex;
	private RelativeLayout edit_doc;
	
	private String fullname = "";
	private String cell = "";
	private String email = "";
	private String sex = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_persondoc);
		mContext = this;

		Intent intent = getIntent();
		if (intent == null) {
			Log.e(TAG, "intent is null");
			return;
		}

		mInputMethodManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

		if (intent.getExtras() != null) {
			mLoginInterface = (LoginInterface) intent.getExtras().getSerializable(
			"LoginInterface");
		}

		findViewById(R.id.main_doc_RelativeLayout_back)
		.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		main_name =(TextView)findViewById(R.id.main_name);
		main_tel =(TextView)findViewById(R.id.main_tel);
		main_email =(TextView)findViewById(R.id.main_email);
		main_sex =(TextView)findViewById(R.id.main_sex);
		edit_doc =(RelativeLayout)findViewById(R.id.edit_doc);
		edit_doc.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(mContext,PersonEditDocumentActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("fullname",fullname);
				bundle.putString("cell",cell);
				bundle.putString("email",email);
				bundle.putString("sex",sex);
				bundle.putSerializable("LoginInterface", mLoginInterface);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if(mLoginInterface!=null){
			getPersonDocument();
		}
	}

	private void openDailogs(String title, final String content) {
		new AlertDialog.Builder(mContext).setTitle(title).setMessage(content)
		.setPositiveButton("确定",  new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				if (content != null && content.trim().equals("用户不存在")) {
					// finish();
				}
				if("登陆失效，需重新登陆".equals(content) || "join(f.username.errors)".equals(content)){
					LoginUtil.executeLoginFaild(mContext);
				}

			}
		}).show();
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (getCurrentFocus() != null
					&& getCurrentFocus().getWindowToken() != null) {
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus()
						.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
		return super.onTouchEvent(event);
	}

	private void getPersonDocument() {
		Network mNetword = new Network(mContext);
		if (!mNetword.isNetworkConnected()) {
			openDailogs("网络提示", "网络未连接,请连接网络！");
		} else {
			String URL = Network.API_DOMAIN+"/profile?user_id="
			+mLoginInterface.getUser_id()+
			"&token="+mLoginInterface.getToken()
			+"&validation="+CRMUserBaseInfo.kValication;

			final ProgressDialog progressDialog = ProgressDialog.show(this, "网络数据", "...Loading...");
			RequestQueue requestQueue = Volley.newRequestQueue(mContext);
			JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(  
					Request.Method.GET,   
					URL,   
					null,  
					new Response.Listener<JSONObject>() {  
						@Override  
						public void onResponse(JSONObject response) {
							ProgressDialogUtil.dissmis(progressDialog);
							try {
								System.out.println("个人档案  response=" + response);
								if (!response.isNull("errors")) {
									String errors = response.get("errors").toString();
									if (errors.equals("[]")) {
										if (!response.isNull("profile")) {
											String profile = response.get("profile").toString();
											JSONObject job = new JSONObject(profile);
											if (!job.isNull("fullname")) {
												fullname = job.get("fullname").toString();
												main_name.setText(fullname);
											}
											if (!job.isNull("cell")) {
												cell = job.get("cell").toString();
												main_tel.setText(cell);
											}
											if (!job.isNull("email")) {
												email = job.get("email").toString();
												main_email.setText(email);
											}
											if (!job.isNull("sex")) {
												sex = job.get("sex").toString();
												main_sex.setText(sex);
											}
										}
										//response={"errors":[],"profile":
										//{"email":"183954573@qq.com",
										//"sex":"男","fullname":"刘德华","cell":"13193323391"}}
									} else {
										org.json.JSONArray jsonArr;
										if (!response.isNull("errors")) {
											LoginError mLoginError = new LoginError();
											jsonArr = response
											.getJSONArray("errors");
											if (jsonArr.length() > 0) {
												for (int i = 0; i < jsonArr
												.length(); i++) {
													JSONObject jsonObj2 = jsonArr
													.getJSONObject(i);
													if (!jsonObj2
															.isNull("desc")) {
														String desc = jsonObj2
														.getString("desc");
														openDailogs("失败提示", desc);
														mLoginError
														.setDesc(desc);
													}
													if (!jsonObj2
															.isNull("value")) {
														String value = jsonObj2
														.getString("value");
														mLoginError
														.setValue(value);
													}
												}
											}
										}
									}
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}  
					},   
					new Response.ErrorListener() {  
						@Override  
						public void onErrorResponse(VolleyError arg0) {  
							ProgressDialogUtil.dissmis(progressDialog);
							System.out.println("sorry,Error");  
						}  
					});  
			requestQueue.add(jsonObjectRequest); 

		}

	}

}